package com.eranga.project.control.data;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

import com.eranga.project.model.AreaCoordinates;

public class AreaCoordinatesDS {
	private SQLiteDatabase dB;
	private DatabaseHelper dbHelper;
	Context context;
	
	public AreaCoordinatesDS (Context context){
		this.context = context;
		dbHelper = new DatabaseHelper(context);
	}
	
	public void open() throws SQLException {
		dB = dbHelper.getWritableDatabase();
	}
	
	
	public int createAreaCoordinates(AreaCoordinates coordinates) {
		if(dB == null){
			open();
		}else if(!dB.isOpen()){
			open();
		}
		
		ContentValues values = new ContentValues();
		values.put(dbHelper.COORDINATES_LATI, coordinates.getCoordinateLatitude());
		values.put(dbHelper.COORDINATES_LONG, coordinates.getCoordinateLongitude());
		values.put(dbHelper.COORDINATES_AREA_ID, coordinates.getCoordinateAreaId());		
		
		int id = (int) dB.insert(dbHelper.TABLE_AREA_COORDINATES, null, values);
		dB.close();
		return id;
		
	}
	
	
	public ArrayList<AreaCoordinates> getAllCoordinates(int id) {
		if (dB == null) {
			open();
		} else if (!dB.isOpen()) {
			open();
		}
		
		ArrayList<AreaCoordinates> results = new ArrayList<AreaCoordinates>();
		
		String selectQuery = "SELECT * FROM " + dbHelper.TABLE_AREA_COORDINATES+" WHERE "+dbHelper.COORDINATES_AREA_ID+"="+id;
		
		Cursor cursor = null;
		cursor = dB.rawQuery(selectQuery, null);
		
		while(cursor.moveToNext()){
			AreaCoordinates coor = new AreaCoordinates();
			
			coor.setCoordinateId(cursor.getInt(cursor.getColumnIndex(dbHelper.COORDINATES_ID)));
			coor.setCoordinateLatitude(cursor.getDouble(cursor.getColumnIndex(dbHelper.COORDINATES_LATI)));
			coor.setCoordinateLongitude(cursor.getDouble(cursor.getColumnIndex(dbHelper.COORDINATES_LONG)));
			coor.setCoordinateAreaId(cursor.getInt(cursor.getColumnIndex(dbHelper.COORDINATES_AREA_ID)));
				
			results.add(coor);
		}
		dB.close();
		return results;
	}
	
}
